package cn.zf233.springsecurityjwt.config;

import cn.zf233.springsecurityjwt.config.handler.JwtAccessDeniedHandler;
import cn.zf233.springsecurityjwt.config.handler.JwtAuthenticationEntryPoint;
import cn.zf233.springsecurityjwt.config.handler.MyFailureHandler;
import cn.zf233.springsecurityjwt.config.handler.MySuccessHandler;
import cn.zf233.springsecurityjwt.config.open.openLoginFilter;
import cn.zf233.springsecurityjwt.config.sms.SmsLoginFilter;
import cn.zf233.springsecurityjwt.config.upwd.UPwdLoginFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.Resource;

/**
 * Created by zf233 on 2021/7/12
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAccessDeniedHandler jwtAccessDeniedHandler;
    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Autowired
    private MyFailureHandler myFailureHandler;
    @Autowired
    private MySuccessHandler mySuccessHandler;
    @Resource
    private UserDetailsService smsDetailsService;
    @Resource
    private AuthenticationProvider smsAuthenticationProvider;
    @Resource
    private UserDetailsService openDetailsService;
    @Resource
    private AuthenticationProvider openAuthenticationProvider;
    @Resource
    private UserDetailsService uPwdDetailsService;
    @Resource
    private AuthenticationProvider uPwdAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // 禁用 CSRF
                .csrf().disable()

                .addFilterBefore(smsLoginFilter(), AbstractPreAuthenticatedProcessingFilter.class)
                .addFilterBefore(openLoginFilter(), AbstractPreAuthenticatedProcessingFilter.class)
                .addFilterBefore(uPwdLoginFilter(), AbstractPreAuthenticatedProcessingFilter.class)

                // 授权异常
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .accessDeniedHandler(jwtAccessDeniedHandler)

                // 防止iframe 造成跨域
                .and()
                .headers()
                .frameOptions()
                .disable()

                // 不创建会话
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                .and()
                .authorizeRequests()

                // 放行静态资源
                .antMatchers(
                        HttpMethod.GET,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/webSocket/**"
                ).permitAll()

                // 放行文件访问
                .antMatchers("/file/**").permitAll()

                // 放行druid
                .antMatchers("/druid/**").permitAll()

                // 放行OPTIONS请求
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

                //允许匿名及登录用户访问
                .antMatchers("/test/hello", "/login/**").permitAll()
                .antMatchers("/test02/no").permitAll()

                // 所有请求都需要认证
                .anyRequest().authenticated();
        // 禁用缓存
        httpSecurity.headers().cacheControl();
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        httpSecurity.addFilterBefore(corsFilter(), JwtAuthenticationTokenFilter.class);
        httpSecurity.addFilterBefore(corsFilter(), LogoutFilter.class);
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOrigin("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 对接口配置跨域设置
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //将两个自定义认证器都注册
        auth.userDetailsService(smsDetailsService)
                .and()
                .authenticationProvider(smsAuthenticationProvider);
        auth.userDetailsService(openDetailsService)
                .and()
                .authenticationProvider(openAuthenticationProvider);
        auth.userDetailsService(uPwdDetailsService)
                .and()
                .authenticationProvider(uPwdAuthenticationProvider);
    }

    //这个必须重写，才能使用AuthenticationManager，在成员变量注入进来，再注入过滤器中
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean("smsLoginFilter")
    public AbstractAuthenticationProcessingFilter smsLoginFilter() throws Exception {
        SmsLoginFilter filter = new SmsLoginFilter(new AntPathRequestMatcher("/login/phone", "POST"));
        filter.setAuthenticationManager(this.authenticationManager());
        filter.setAuthenticationSuccessHandler(mySuccessHandler);
        filter.setAuthenticationFailureHandler(myFailureHandler);
        return filter;
    }

    @Bean("openLoginFilter")
    public AbstractAuthenticationProcessingFilter openLoginFilter() throws Exception {
        openLoginFilter filter = new openLoginFilter(new AntPathRequestMatcher("/login/open", "POST"));
        filter.setAuthenticationManager(this.authenticationManager());
        filter.setAuthenticationSuccessHandler(mySuccessHandler);
        filter.setAuthenticationFailureHandler(myFailureHandler);
        return filter;
    }

    @Bean("uPwdLoginFilter")
    public AbstractAuthenticationProcessingFilter uPwdLoginFilter() throws Exception {
        UPwdLoginFilter filter = new UPwdLoginFilter(new AntPathRequestMatcher("/login", "POST"));
        filter.setAuthenticationManager(this.authenticationManager());
        filter.setAuthenticationSuccessHandler(mySuccessHandler);
        filter.setAuthenticationFailureHandler(myFailureHandler);
        return filter;
    }
}